<template>
  <div>
    <!-- 卡片视图 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="12">
          <!-- 查找企业 -->
          <SearchBar
            :queryInfo="queryInfo"
            @searchByName="searchCompany"
            @clearInput="clearInput"
            @searchByArea="searchBusiness"
          ></SearchBar>
        </el-col>
        <!-- 添加企业模块 -->
        <el-col :span="12">
          <div class="right">
            <el-button type="success" plain @click="excelShow">
              导出Excel表格
            </el-button>
            <!-- 批量导入企业 -->
            <el-button type="success" plain @click="excelImport">
              批量导入
            </el-button>
            <el-button type="primary" @click="addBusiness">
              添加企业
            </el-button>
          </div>
          
          <el-dialog title="添加企业" :visible.sync="dialogVisible" width="50%">
            <el-form
              :label-position="labelPosition"
              label-width="100px"
              :model="companyForm"
              :rules="companyRules"
            >
              <el-form-item label="企业名称:" prop="name">
                <el-input
                  v-model="companyForm.name"
                  placeholder="请输入企业名"
                ></el-input>
              </el-form-item>
              <el-form-item label="所属地:" prop="merName">
                <el-cascader
                  size="large"
                  :options="options"
                  v-model="selectedOptions"
                  @change="handleChange"
                >
                </el-cascader>
              </el-form-item>
              <el-form-item label="地址:" prop="address">
                <el-input
                  v-model="companyForm.address"
                  placeholder="请输入详细地址"
                ></el-input>
              </el-form-item>
              <el-form-item label="邮编:" prop="uscc">
                <el-input v-model="companyForm.uscc"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="confirm">确 定</el-button>
            </span>
          </el-dialog>
        </el-col>
      </el-row>

      <!-- 展示所有企业 -->
      <el-table :data="business" style="width: 100%; top: 20px">
        <el-table-column fixed prop="name" label="企业名称"> </el-table-column>
        <el-table-column prop="cityInfo.merName" label="所属地">
        </el-table-column>
        <el-table-column prop="address" label="地址"> </el-table-column>
        <el-table-column prop="uscc" label="邮编"> </el-table-column>
        <el-table-column prop="createTime" label="创建时间"> </el-table-column>
        <el-table-column prop="modiTime" label="编辑时间"> </el-table-column>
        <el-table-column fixed="right" label="操作">
          <template slot-scope="scope">
            <el-button @click="edit(scope.row)" type="text" icon="el-icon-edit" size="small"
              >编辑</el-button
            >
            <el-button @click="deleteById(scope.row.id)" type="text" style="color: #fa6962" icon="el-icon-delete" size="small"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[5, 10, 15]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import { provinceAndCityData } from "element-china-area-data"; //引入
import SearchBar from "@/components/OrganizationManagement/SearchBar.vue";
import {
  getBusiness,
  addBusiness,
  searchBusiness,
  updateBusiness,
  deleteBusiness,
  importBdDeptdoc,
  searchBusinessByCity,
} from "#/OrganizationManagement/business.js";
import { addLogs } from "#/Home/Home.js";
export default {
  name: "Business",
  meta: {
    title: "企业管理",
  },
  components: {
    SearchBar
  },
  data() {
    return {
      queryInfo: {
        //查询的内容
        query: "",
        // 当前页数
        pageNum: 1,
        // 每页显示多少数据
        pageSize: 5,
      },
      business: [],
      select: "",
      //总数据条数
      total: 0,
      //添加企业弹窗
      dialogVisible: false,
      labelPosition: "right",
      companyForm: {
        name: "",
        provinceName: "",
        cityName: "",
        address: "",
        city: "",
      },
      companyRules: {
        name: [
          { required: true, message: "请输入企业名称", trigger: "blur" }
        ],
        merName: [
          { required: true, message: "请选择所属地", trigger: "blur" }
        ],
        address: [
          { required: true, message: "请输入地址", trigger: "blur" }
        ],
        uscc: [
          { required: true, message: "请输入邮编", trigger: "blur" }
        ],
      },
      excelImportShow: false,
      fileList: [],
      fileName: "",
      addLoading: false,
      options: provinceAndCityData,
      selectedOptions: []
    };
  },
  created() {
    this.getCompany();
  },
  methods: {
    // 所有机构（企业）信息
    async getCompany() {
      await getBusiness(this.queryInfo.pageNum, this.queryInfo.pageSize).then(
        (res) => {
          const result = res.data;
          console.log(result);
          if (result.ret === 0) {
            this.business = result.orgs.ents.content;
            this.total = result.orgs.ents.totalElements;
          } else {
            this.$message.error("服务器请求错误！");
          }
        }
      );
    },
    clearInput() {
      this.queryInfo.pageNum = 1;
      this.queryInfo.pageSize = 5;
      this.getCompany();
    },
    // 通过地区搜索企业
    async searchBusiness(queryOptions) {
      this.queryInfo.pageNum = 1;
      this.queryInfo.pageSize = 5;
      if (queryOptions.length === 0) {
        this.getCompany();
      } else {
        await searchBusinessByCity(this.queryInfo, +queryOptions[1]).then(
          (res) => {
            if (res.data.ret === 0) {
              this.business = res.data.orgs.ents.content;
              this.total = res.data.orgs.ents.totalElements;
            }
          }
        );
      }
    },
    confirm() {
      if (this.addFlag) {
        addBusiness(this.companyForm).then((res) => {
          if (res.data.ret == 0) {
            this.$message.success("添加成功");
            this.dialogVisible = false;
            addLogs({
              userId: window.sessionStorage.getItem("userId"),
              behavior: "添加了新的企业信息",
            });
          }
          this.getCompany();
        });
      } else {
        updateBusiness(this.companyForm.id, this.companyForm).then((res) => {
          if (res.data.ret == 0) {
            this.$message.success("修改成功");
            this.dialogVisible = false;
            addLogs({
              userId: window.sessionStorage.getItem("userId"),
              behavior: "修改了企业信息",
            });
          }
          this.getCompany();
        });
      }
    },
    edit(obj) {
      this.selectedOptions = [obj.cityInfo.pid + "", obj.cityInfo.id + ""];
      this.addFlag = false;
      Object.assign(this.companyForm, obj);
      this.dialogVisible = true;
    },
    //通过企业名模糊搜索企业
    async searchCompany() {
      if (!this.queryInfo.query) {
        return this.$message.error("请输入名称");
      }
      this.queryInfo.pageNum = 1;
      await searchBusiness(this.queryInfo).then((res) => {
        if (res.status === 200) {
          this.business = res.data.orgs.ents.content;
          this.total = res.data.orgs.ents.totalElements;
          if (this.business === []) {
            this.$message.info("搜索结果为空");
          } else {
            this.$message.success("搜索成功！");
          }
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    handleChange(value) {
      // value = CodeToText(value);
      this.companyForm.city = value[1];
    },
    addBusiness() {
      this.dialogVisible = true;
      this.addFlag = true;
      this.companyForm = {
        name: "",
        address: "",
        city: "",
        uscc: "",
      };
    },
    deleteById(id) {
      this.$confirm(
        "此操作将永久删除该企业, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(confirmResult => {
        if (confirmResult === "confirm") {
        deleteBusiness(id).then((res) => {
          if (res.data.ret == 0) {
            this.$message.success("删除成功！");
            addLogs({
              userId: window.sessionStorage.getItem("userId"),
              behavior: "成功删除了企业信息",
            });
          }
          this.getCompany();
        });
      }
      }).catch((err) => err);
      
    },
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.getCompany();
    },
    // 页码改变
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage;
      this.getCompany();
    },
    beforeUpload(file) {
      console.log(file, "文件");
      this.files = file;
      const extension = file.name.split(".")[1] === "xls";
      const extension2 = file.name.split(".")[1] === "xlsx";
      // const isLt2M = file.size / 1024 / 1024 < 5(校验上传文件的大小)
      if (!extension && !extension2) {
        this.$message.warning("上传文档只能是 xls、xlsx格式!");
        return;
      }
      console.log(file.name);
      this.fileName = file.name;
      return false; // 返回false不会自动上传
    },
    submitUpload() {
      if (this.fileName == "") {
        this.$message.warning("请选择要上传的文件！");
        return false;
      }
      let fileFormData = new FormData();
      fileFormData.append("file", this.files); //filename是键，file是值，就是要传的文件，test.zip是要传的文件名
      importBdDeptdoc(fileFormData).then((res) => {
        this.addLoading = false;
        this.$message({
          message: "导入成功",
          type: "success",
        });
        this.getCompany(); //重新请求一次页面数据
      });
    },
    excelShow() {
      this.$message.error('暂无功能')
    },
    excelImport() {}
  },
};
</script>

<style scoped>
.right {
  float: right;
}
</style>
